<template>
  <n-modal
    v-model:show="modalVisible"
    preset="card"
    display-directive="if"
    :auto-focus="false"
    :mask-closable="false"
    :close-on-esc="false"
    style="width: 320px"
    title="获取对账单"
    :bordered="true"
  >
    <n-form ref="formRef" :model="formModel" :rules="rules" @submit="handleSubmit">
      <n-form-item label="对账单种类" path="billClass">
        <n-select v-model:value="formModel.billClass" :options="billClassOptions" placeholder="选择对账单种类" />
      </n-form-item>
      <n-form-item label="对账单类型" path="billType">
        <n-select v-model:value="formModel.billType" :options="billTypeOptions" placeholder="选择对账单类型" />
      </n-form-item>
      <n-form-item label="日期范围" path="dateRange">
        <shortcuts-rangdata v-model:value="formModel.dateRange" />
      </n-form-item>
      <n-row :gutter="[24, 24]">
        <n-col :span="24" class="flex justify-end">
          <n-button type="primary" attr-type="submit">确认</n-button>
        </n-col>
      </n-row>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import type { FormInst } from 'naive-ui';
import { useDateFormat } from '@vueuse/core';
import { fetchNewBill } from '@/service';
import { useBillContext } from '@/context';
import { createRequiredFormRule } from '@/utils';
import shortcutsRangdata from './ShortcutsRangdata.vue';
export interface Props {
  /** 弹窗可见性 */
  visible: boolean;
}
interface Emits {
  (e: 'update:visible', visible: boolean): void;
}
const props = withDefaults(defineProps<Props>(), {
  visible: false
});
const emit = defineEmits<Emits>();
const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible) {
    emit('update:visible', visible);
  }
});

const { useInject } = useBillContext();
const { setBillNo, setNewBill, setBillStatus } = useInject();

const formRef = ref<HTMLElement & FormInst>();

const formModel = reactive(createDefaultFormModel());

const rules: any = reactive({
  billClass: createRequiredFormRule('请选择对账单种类'),
  billType: createRequiredFormRule('请选择对账单类型'),
  dateRange: createRequiredFormRule('请选择日期范围')
});

const billClassOptions = [
  {
    label: '采购对账单',
    value: '1'
  },
  {
    label: '委外对账单',
    value: '2'
  }
];

const billTypeOptions = [
  {
    label: '售前对账单',
    value: '1'
  },
  {
    label: '售后对账单',
    value: '2'
  }
];

function createDefaultFormModel(): any {
  const now = new Date();
  const cur = now.getTime();
  const nowDay = now.getDate() - 1;
  return {
    billClass: null,
    billType: null,
    dateRange: [cur - nowDay * 24 * 60 * 60 * 1000, cur] as const
  };
}
function handleUpdateFormModel(model: any) {
  Object.assign(formModel, model);
}
function handleSubmit(e: any) {
  e.preventDefault();
  setBillNo('');
  setNewBill(false);
  setBillStatus(0);
  formRef.value
    ?.validate(async errors => {
      if (!errors) {
        const { billClass, billType, dateRange } = formModel;
        let beginDate = useDateFormat(dateRange[0], 'YYYY/MM/DD').value;
        let endDate = useDateFormat(dateRange[1], 'YYYY/MM/DD').value;
        beginDate = useDateFormat(beginDate, 'YYYY/MM/DD').value;
        endDate = useDateFormat(endDate, 'YYYY/MM/DD').value;
        const res: any = await fetchNewBill({ billClass, billType, beginDate, endDate });
        if (res.data.billId) {
          window.$message?.success(`获取对账单成功！`);
          setBillNo(res.data.billId);
          setNewBill(true);
          modalVisible.value = false;
          const defaultFormModel = createDefaultFormModel();
          handleUpdateFormModel(defaultFormModel);
        } else {
          window.$message?.error(`未获取到对账单ID！`);
        }
      }
    })
    .catch(() => {});
}
</script>
